<?xml version="1.0" encoding="utf-8"?>
<mx:ApolloApplication xmlns:mx="http://www.adobe.com/2006/mxml" pageTitle="Apollo In Flight" creationComplete="initApp()" layout="vertical" backgroundColor="#000040" width="380" height="275">

    <mx:WebService id="wsFlight" wsdl="http://labs.insideflex.com/apollotraining/gofly/info/flexination/cfcs/flight.cfc?wsdl" showBusyCursor="true">
        <mx:operation name="getFlightDetails" result="getFlightDetailsHandler(event)" fault="wsfaultHandler(event)"/>
    </mx:WebService>
    <mx:Script>
        <![CDATA[
            import mx.controls.HTML;
            import mx.rpc.events.ResultEvent;
            import mx.rpc.events.FaultEvent;
            import mx.controls.Alert;
            import mx.utils.ObjectUtil;
            import mx.containers.TitleWindow;
            import mx.events.ValidationResultEvent;
            import mx.controls.ToolTip;
            import mx.managers.ToolTipManager;
            import info.flexination.actionscripts.ConnectionStatus;

            [Bindable] public var txtFlightInfo:String = "";
            [Bindable] public var blnConnected:Boolean = true;
            private var vResult:ValidationResultEvent;
            private var msg:String = "";
            private var count:Number = 0;
            private var msgprefix:String = "";
            private var ErrorTip:ToolTip;
            public var newWindow:NativeWindow;
            private var component:FlightDetails;
            private var myTimer:Timer = new Timer(360000, 0);
            public var blnWindowOpen:Boolean = false;
            private var connection:ConnectionStatus = new ConnectionStatus();
            
            private function initApp():void {
                // add an NETWORK_CHANGE event listener: Listens for the connectivity status
                Shell.shell.addEventListener(Event.NETWORK_CHANGE, connection.onConnectionChange);
                // calls the function that checks the connectivity
                connection.checkConnection();
                myTimer.addEventListener("timer", onTimer);
            }

            private function createWindow():void {
                newWindow = new NativeWindow( true, new NativeWindowInitOptions() );
                newWindow.title = "Apollo in Flight Details: " + tiAirline.text + tiFlightNo.text;
                component = new FlightDetails();
                hiddenVBox.addChild(component);
                hiddenVBox.removeChild(component);
                newWindow.stage.addChild(component);
                blnWindowOpen = true;
            }
            
            private function getFlightDetailsHandler(event:ResultEvent):void {
                txtFlightInfo = wsFlight.getFlightDetails.lastResult as String;
                //Alert.show(ObjectUtil.toString(txtFlightInfo));
                lblProgress.text = "";
                lblProgress.visible = false;
                myTimer.start();
                if (!blnWindowOpen) {
                    createWindow();
                } else {
                    component.fillFlightInfo();
                }
            }

            private function wsfaultHandler(event:FaultEvent):void {
                // dump error message
                //Alert.show(ObjectUtil.toString(event.fault));
                Alert.show("GoFly couldn't find Flight " + tiAirline.text + tiFlightNo.text + " just yet.", "Flight Details Unavailable");
                // parse the flight
                var flight:String = tiAirline.text + tiFlightNo.text;
                // call the flight WebService
                wsFlight.getFlightDetails(flight);
                lblProgress.text = "Retrieving flight data...";
                lblProgress.visible = true;
            }

            private function onTimer(event:TimerEvent):void {
                    // parse the flight
                    var flight:String = tiAirline.text + tiFlightNo.text;
                    // call the flight WebService
                    wsFlight.getFlightDetails(flight);
                    lblProgress.text = "Retrieving flight data...";
                    lblProgress.visible = true;
                    myTimer.stop();
            }

            private function validateForm():void {
                msg = "";
                count = 0;
                // Validate the Airline. 
                vResult = vAirline.validate();
                // If the Airline is invalid.
                if (vResult.type==ValidationResultEvent.INVALID) {
                    msg = "You must enter an Airline symbol (e.g. FFT = Frontier Airlines).\n\n";
                    count++;
                }
                // Validate the FlightNo. 
                vResult = vFlightNo.validate();
                // If the FlightNo is invalid.
                if (vResult.type==ValidationResultEvent.INVALID) {
                    msg = msg + "You must enter a Flight Number (e.g. 663).\n\n";
                    count++;
                }
                if (msg!="") {
                    if (count>1) {
                        msgprefix = "You must correct the following issues:";
                    }
                    mx.controls.Alert.show(msgprefix + "\n\n" + msg, "Required Fields Alert...");
                    return;
                } else {
                    // parse the flight
                    var flight:String = tiAirline.text + tiFlightNo.text;
                    // call the flight WebService
                    wsFlight.getFlightDetails(flight);
                    lblProgress.text = "Retrieving flight data...";
                    lblProgress.visible = true;
                }
            }
            
            private function goThere(sURL:String):void {
                   var u:URLRequest = new URLRequest(sURL);
                navigateToURL(u,"_blank");
            }
        ]]>
    </mx:Script>

    <mx:Style>
        Panel {
           borderColor: #666666;
           borderAlpha: 0.4;
           roundedBottomCorners: true;
           headerHeight: 22;
           backgroundAlpha: 1;
           backgroundColor: #000000;
           titleStyleName: "mypanelTitle";
        }
        
        .mypanelTitle {
           color: #ff3300;
           textAlign: left;
           fontSize: 12;
           fontWeight: bold;
           fontStyle: italic;
           paddingLeft: 20;
        }
    </mx:Style>
    
    <mx:Style>
       ToolTip { font-family: "Verdanna"; font-size: 12; font-weight: "normal"; background-color: "0x7B68EE"; color: "0xFFFFFF"; }
    </mx:Style>

    <!-- Define validators. -->
    <mx:StringValidator id="vAirline" source="{tiAirline}" property="text" requiredFieldError="Please enter an Airline symbol (e.g. FFT = Frontier Airlines)."/>
    <mx:StringValidator id="vFlightNo" source="{tiFlightNo}" property="text" requiredFieldError="Please enter a Flight Number (e.g. 663)."/>

    <mx:Panel id="pnlGoFly" title="Apollo Flight Info">
        <mx:Form id="frmFlight" width="280" height="130" backgroundColor="#000040">
            <mx:FormItem>
                <mx:HBox width="100%">
                    <mx:Spacer width="41"/>
                    <mx:Label text="Airline:" fontFamily="Verdana" fontSize="12" color="#ffffff" textAlign="right"/>
                    <mx:TextInput id="tiAirline" width="80" toolTip="Please enter an Airline symbol (e.g. FFT = Frontier Airlines)..."/>
                </mx:HBox>
            </mx:FormItem>
            <mx:FormItem>
                <mx:HBox width="100%">
                    <mx:Label text="Flight Number:" fontFamily="Verdana" fontSize="12" color="#ffffff" textAlign="right"/>
                    <mx:TextInput id="tiFlightNo" width="80" toolTip="Please enter a Flight Number (e.g. 663)..."/>
                </mx:HBox>
            </mx:FormItem>
            <mx:Label id="lblProgress" color="#ff3300" fontStyle="italic" fontSize="11" fontWeight="bold"/>
            <mx:VBox id="hiddenVBox" visible="false"/>
        </mx:Form>
        <mx:ControlBar>
            <mx:HBox width="100%">
                <mx:Button id="btnSearch" label="Search" click="validateForm()" fontFamily="Verdanna" fontSize="14" fontWeight="bold" toolTip="{(blnConnected)?'Click to search for this flight...':'Offline mode - button is currently inactive...'}"/>
                <mx:Button id="btnViewSource" label="Source" click="goThere('http://labs.insideflex.com/apollotraining/gofly/bin/srcview/index.html')" fontFamily="Verdanna" fontSize="14" fontWeight="bold" toolTip="{(blnConnected)?'Click to view the source code...':'Offline mode - button is currently inactive...'}"/>
                <mx:Button id="btnExit" label="Exit" click="window.close()" fontFamily="Verdanna" fontSize="14" fontWeight="bold" toolTip="Click to exit this application..."/>
                <mx:Spacer width="30"/>
                <mx:Image id="imgStatus" width="24" height="24"/>
            </mx:HBox>
        </mx:ControlBar>
    </mx:Panel>
    
</mx:ApolloApplication>